package org.zbclan.bf2.rcon.client;

import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.UIDL;

public class VHello extends Hello implements Paintable {

	private ApplicationConnection client;
	private String uidlId;

	@Override
	public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {

		if (client.updateComponent(this, uidl, true)) {
			return;
		}

		// Save reference to server connection object to be able to send
		// user interaction later
		this.client = client;

		// Save the UIDL identifier for the component
		uidlId = uidl.getId();

		setText(uidl.getStringVariable("text"));
	}

	@Override
	public void setText(String text) {

		// Ignore if no change
		boolean textMatch = (text != null && text.equals(getText()))
				|| (text == null && getText() == null);
		if (textMatch) {
			return;
		}

		// Let the original implementation to do whatever it needs to do
		super.setText(text);

		// Updating the state to the server can not be done before
		// the server connection is known, i.e., before updateFromUIDL()
		// has been called.
		if (uidlId == null || client == null) {
			return;
		}

		// Communicate the user interaction parameters to server. This call will
		// initiate an AJAX request to the server.
		client.updateVariable(uidlId, "text", text, true);

		return;
	}
}
